package com.sgb.kjwl.view.ui.activity.self.logistics;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.bigkoo.pickerview.view.OptionsPickerView;
import com.fondesa.recyclerviewdivider.DividerDecoration;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityCargoPublishMoreBinding;
import com.sgb.kjwl.di.transport.DaggerTransportComponent;
import com.sgb.kjwl.di.transport.TransportModule;
import com.sgb.kjwl.model.entity.transport.CargoPublishEntity;
import com.sgb.kjwl.model.entity.transport.CompanyInvoiceEntity;
import com.sgb.kjwl.model.entity.transport.GoodsInfoTypeEntity3;
import com.sgb.kjwl.model.entity.transport.InvoiceRateEntity;
import com.sgb.kjwl.model.entity.transport.SingleItemEntity;
import com.sgb.kjwl.utils.DefaultUtil;
import com.sgb.kjwl.utils.NumberUtil;
import com.sgb.kjwl.utils.PickerHelper;
import com.sgb.kjwl.utils.RangeFocusChangeListener;
import com.sgb.kjwl.view.constant.RouterKey;
import com.sgb.kjwl.view.ui.adapter.CargoInvoiceAdapter;
import com.sgb.kjwl.view.ui.adapter.transport.CargoCustomValueAdapter;
import com.sgb.kjwl.view.widget.InvoicingCompanyPopWindow;
import com.sgb.kjwl.view.widget.SwitchButton2;
import com.swgk.core.dialog.RoundDialog;
import com.sgb.kjwl.viewmodel.transport.CargoPublishMoreViewModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.util.DensityUtils;
import com.swgk.core.util.CheckUtils;
import com.swgk.core.util.MToast;
import com.zjkj.qgbui.widgets.SwitchButton;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.inject.Inject;

/**
 * @author: 杨畔
 * @date: 2020/12/29 17:50
 * @Description: 货源发布填写更多信息页面
 */
public class CargoPublishMoreActivity extends AppActivity {

    @Inject
    CargoPublishMoreViewModel viewModel;
    ActivityCargoPublishMoreBinding binding;
    //选择弹窗
    private OptionsPickerView<GoodsInfoTypeEntity3> mPayPicker;
    private OptionsPickerView<InvoiceRateEntity> mInvoicePicker;
    private OptionsPickerView<GoodsInfoTypeEntity3> mRequirePicker;
    private InvoicingCompanyPopWindow mCompanyPop;
    //自定义字段列表
    private List<SingleItemEntity> mCustomList;
    private CargoCustomValueAdapter mCustomAdapter;
    //开票信息
    private List<SingleItemEntity> mList;
    private CargoInvoiceAdapter mAdapter;
    //数据实体类
    private CargoPublishEntity mEntity;

    public static void start(Activity activity, CargoPublishEntity entity, int requestCode) {
        Intent intent = new Intent(activity, CargoPublishMoreActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.putExtra(RouterKey.DATA, entity);
        activity.startActivityForResult(intent, requestCode);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerTransportComponent.builder()
                .appComponent(appComponent)
                .transportModule(new TransportModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void init() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_cargo_publish_more);
        binding.setLifecycleOwner(this);
        binding.includeTitle.titleView.setText("更多信息");
        initPopup();
        initRecycler();
        initEvent();
        initData();
    }

    private void initPopup() {
        mCompanyPop = new InvoicingCompanyPopWindow(this);
        mCompanyPop.setOnResultClick((key1, key2, key3) -> {
            if (key1 == null) return;
            CompanyInvoiceEntity entity = (CompanyInvoiceEntity) key1;
            //添加属性
            mEntity.setInvoicingCompanyName(entity.getCompanyName());
            mEntity.setInvoicingTaxNumber(entity.getCreditCode());
            mEntity.setInvoicingAddress(entity.getAddress());
            mEntity.setInvoicingCompanyPhone(entity.getPhone());
            mEntity.setInvoicingBank(entity.getBank());
            mEntity.setInvoicingBankAccount(entity.getBankAccount());
            mEntity.setInvoicingBankNumber(entity.getBankNumber());
            //设置公司信息
            syncCompanyInvoice();
        });
    }

    private void initRecycler() {
        //公司开票信息
        mList = new ArrayList<>();
        mAdapter = new CargoInvoiceAdapter(mList);
        binding.rvReleaseCargoInfo.setLayoutManager(new LinearLayoutManager(this));
        DividerDecoration.builder(this)
                .colorRes(R.color.color_line)
                .size(1, TypedValue.COMPLEX_UNIT_PX)
                .insets(DensityUtils.dip2px(getActivity(),14), DensityUtils.dip2px(getActivity(),14))
                .build()
                .addTo(binding.rvReleaseCargoInfo);
        mAdapter.bindToRecyclerView(binding.rvReleaseCargoInfo);
        //自定义字段
        mCustomList = new ArrayList<>();
        mCustomAdapter = new CargoCustomValueAdapter(mCustomList);
        binding.rvReleaseCargoField.setNestedScrollingEnabled(false);
        binding.rvReleaseCargoField.setLayoutManager(new LinearLayoutManager(this));
        DividerDecoration.builder(this)
                .colorRes(R.color.transparent)
                .showFirstDivider()
                .size(10, TypedValue.COMPLEX_UNIT_DIP)
                .build()
                .addTo(binding.rvReleaseCargoField);
        mCustomAdapter.bindToRecyclerView(binding.rvReleaseCargoField);
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initEvent() {
        binding.setOnClick(this);
        binding.includeTitle.ivBack.setOnClickListener(this);
        //自定义字段删除监听
        mCustomAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.iv_release_cargo_del) {
                mCustomList.remove(position);
                mCustomAdapter.notifyDataSetChanged();
            }
        });
        //设置输入范围
        binding.etReleaseCargoArrivalTime.setOnFocusChangeListener(new RangeFocusChangeListener(1, 999));
        binding.etReleaseCargoPerformanceBond.setOnFocusChangeListener(new RangeFocusChangeListener(10, 50000));
        //接口回调
        viewModel.ldPay.observe(this, this::syncPayType);
        viewModel.ldInvoiceRateEntity.observe(this, this::syncInvoice);
        viewModel.ldRequire.observe(this, this::syncRequire);
        viewModel.ldCompanyInvoice.observe(this, entity -> mCompanyPop.setData(entity));
        //货主信息是否展示 0:不展示 1:展示
        binding.isShowInfo.setOnCheckedChangeListener(new SwitchButton2.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton2 button, boolean checked) {
                if (checked) {
                    mEntity.setWhetherShow(1);
                } else {
                    mEntity.setWhetherShow(0);
                }
            }
        });
    }

    private void initData() {
        mEntity = getIntent().getParcelableExtra(RouterKey.DATA);
        if (mEntity == null) {
            mEntity = new CargoPublishEntity();
        } else {
            syncData();
        }
        //获取页面数据
        viewModel.getPayType();
        viewModel.getInvoices(this);
        viewModel.getRequire();
        viewModel.getInvoiceList(this);
    }

    private void syncData() {
        if (mEntity.getArrivalTime() != null && mEntity.getArrivalTime() != 0) {
            binding.etReleaseCargoArrivalTime.setText(NumberUtil.trim0(mEntity.getArrivalTime()));
        }
        if (mEntity.getPerformanceBond() != null && mEntity.getPerformanceBond() != 0) {
            binding.etReleaseCargoPerformanceBond.setText(NumberUtil.trim0(mEntity.getPerformanceBond()));
        }
        //装车/卸车要求
        binding.tvReleaseCargoRequire.setText(viewModel.getRequireStr(mEntity.getRequire()));
        if (!TextUtils.isEmpty(mEntity.getLostPromise())) {
            binding.etReleaseCargoLost.setText(mEntity.getLostPromise());
        }
        if (!TextUtils.isEmpty(mEntity.getOverduePromise())) {
            binding.etReleaseCargoOverdue.setText(mEntity.getOverduePromise());
        }
        if (!TextUtils.isEmpty(mEntity.getOtherPromise())) {
            binding.etReleaseCargoOther.setText(mEntity.getOtherPromise());
        }
        if (!TextUtils.isEmpty(mEntity.getMark())) {
            binding.etReleaseCargoMark.setText(mEntity.getMark());
        }
        if (!TextUtils.isEmpty(mEntity.getPayType())) {
            binding.tvReleaseCargoPayWay.setText(mEntity.getPayType());
        }
        if (!TextUtils.isEmpty(mEntity.getReceiptAccountRequire())) {
            binding.etReleaseCargoAccount.setText(mEntity.getReceiptAccountRequire());
        }
        if (!TextUtils.isEmpty(mEntity.getOtherPaymentRequire())) {
            binding.etReleaseCargoOtherPayMark.setText(mEntity.getOtherPaymentRequire());
        }
        //发票要求信息
        checkInvoiceInfo();
        //设置公司信息
        if (!TextUtils.isEmpty(mEntity.getInvoicingCompanyName())) {
            syncCompanyInvoice();
        }
        //自定义字段
        if (mEntity.getCustomList() != null && !mEntity.getCustomList().isEmpty()) {
            mCustomList.addAll(mEntity.getCustomList());
            mCustomAdapter.notifyDataSetChanged();
        }
        //货主信息是否展示 0:不展示 1:展示
        if (mEntity.getWhetherShow() == 1) {
            binding.isShowInfo.setChecked(true);
        }else{
            binding.isShowInfo.setChecked(false);
        }

        if(!TextUtils.isEmpty(mEntity.getShipperOwnerUnit())){
            binding.etCompany.setText(mEntity.getShipperOwnerUnit());
        }

        if(!TextUtils.isEmpty(mEntity.getShipperContact())){
            binding.etContacts.setText(mEntity.getShipperContact());
        }

        if(!TextUtils.isEmpty(mEntity.getShipperPhone())){
            binding.etPhone.setText(mEntity.getShipperPhone());
        }

    }

    /**
     * 设置付款方式
     */
    private void syncPayType(List<GoodsInfoTypeEntity3> list) {
        mPayPicker = PickerHelper.with(this).getCommonPicker("选择付款方式", list, (options1, options2, options3, v) -> {
            GoodsInfoTypeEntity3 entity = list.get(options1);
            //设置数据
            mEntity.setPayType(entity.getName());
            //设置回显
            binding.tvReleaseCargoPayWay.setText(DefaultUtil.getString(entity.getName()));
        });
    }

    /**
     * 设置发票要求
     */
    private void syncInvoice(List<InvoiceRateEntity> list) {
        if (list == null) return;
        mInvoicePicker = PickerHelper.with(this).getCommonPicker("发票要求", list, (options1, options2, options3, v) -> {
            InvoiceRateEntity entity = list.get(options1);
            //设置数据
            if (!TextUtils.isEmpty(entity.getRate()))
                mEntity.setTariff(Double.parseDouble(entity.getRate()));
            if (!TextUtils.isEmpty(entity.getNo()))
                mEntity.setInvoiceNo(entity.getNo());
            if (!TextUtils.isEmpty(entity.getInvoiceRequest()))
                mEntity.setInvoice(entity.getInvoiceRequest());

            //设置回显
            binding.tvReleaseCargoInvoice.setText(DefaultUtil.getString(entity.getName()));
        });
    }

    /**
     * 发票要求信息匹配检测
     */
    private void checkInvoiceInfo() {
        if (mEntity.isInvoiceChanges()) {
            mEntity.setInvoiceNo("");
            mEntity.setInvoice("");
            mEntity.setTariff(null);
        } else if (!TextUtils.isEmpty(mEntity.getInvoice()) && mEntity.getTariff() != null && !TextUtils.isEmpty(mEntity.getInvoiceNo())) {
            if (mEntity.getInvoice().equals("不开发票")) {
                binding.tvReleaseCargoInvoice.setText(mEntity.getInvoice());
            } else {
                String invoiceStr = NumberUtil.trim0(mEntity.getTariff()) + "%" + mEntity.getInvoice();
                binding.tvReleaseCargoInvoice.setText(invoiceStr);
            }
        }
    }

    /**
     * 设置公司信息
     */
    private void syncCompanyInvoice() {
        binding.tvReleaseCargoCompany.setText(DefaultUtil.getString(mEntity.getInvoicingCompanyName()));
        mList.clear();
        mList.add(new SingleItemEntity("税号", mEntity.getInvoicingTaxNumber()));
        mList.add(new SingleItemEntity("地址", mEntity.getInvoicingAddress()));
        mList.add(new SingleItemEntity("企业电话", mEntity.getInvoicingCompanyPhone()));
        mList.add(new SingleItemEntity("开户银行", mEntity.getInvoicingBank()));
        mList.add(new SingleItemEntity("银行账号", mEntity.getInvoicingBankAccount()));
        mList.add(new SingleItemEntity("开户行行号", mEntity.getInvoicingBankNumber()));
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 设置装卸要求
     */
    private void syncRequire(List<GoodsInfoTypeEntity3> list) {
        mRequirePicker = PickerHelper.with(this).getCommonPicker("选择装车要求", list, (options1, options2, options3, v) -> {
            GoodsInfoTypeEntity3 entity = list.get(options1);
            //设置数据
            mEntity.setRequire(NumberUtil.convertToInt(entity.getNo()));
            //设置回显
            binding.tvReleaseCargoRequire.setText(DefaultUtil.getString(entity.getName()));
        });
    }

    @Override
    public void onClick(View v) {
        closeKeybord();
        if (v == binding.includeTitle.ivBack) {
            finish();
        } else if (v == binding.tvReleaseCargoArrivalTimeTip) {
            showArrivalTimeTipDialog();
        } else if (v == binding.llReleaseCargoRequire) {
            if (mRequirePicker != null) {
                mRequirePicker.show();
            }
        } else if (v == binding.llReleaseCargoPayWay) {
            if (mPayPicker != null) {
                mPayPicker.show();
            }
        } else if (v == binding.llReleaseCargoInvoice) {
            if (mInvoicePicker != null) {
                mInvoicePicker.show();
            }
        } else if (v == binding.llReleaseCargoCompany) {
            mCompanyPop.showDownPopwindow(binding.tvReleaseCargoSubmit, true);
            mCompanyPop.backgroundAlpha(0.5f);
        } else if (v == binding.tvReleaseCargoAdd) {
            //添加更多字段
            addField();
        } else if (v == binding.tvReleaseCargoSubmit) {
            clearAllFocus();
            checkData();
        }
    }

    private void showArrivalTimeTipDialog() {
        new RoundDialog.Builder(this)
                .content("到货时间：开始运输后多少日到货")
                .confirm("关闭")
                .singleBtn(true)
                .show();
    }

    /**
     * 添加更多字段
     */
    private void addField() {
        if (mCustomList.size() >= 3) {
            MToast.showToast(this, "最多添加3个字段");
            return;
        }
        mCustomList.add(new SingleItemEntity());
        mCustomAdapter.notifyDataSetChanged();
    }

    /**
     * 检查数据并回传
     */
    private void checkData() {
        if (mEntity == null) return;
        if (binding.etReleaseCargoArrivalTime.getText() != null) {
            mEntity.setArrivalTime(NumberUtil.convertToInt(binding.etReleaseCargoArrivalTime.getText().toString()));
        } else {
            mEntity.setArrivalTime(null);
        }
        if (binding.etReleaseCargoPerformanceBond.getText() != null) {
            mEntity.setPerformanceBond(NumberUtil.convertToDouble(binding.etReleaseCargoPerformanceBond.getText().toString()));
        } else {
            mEntity.setPerformanceBond(null);
        }
        if (binding.etReleaseCargoLost.getText() != null) {
            mEntity.setLostPromise(binding.etReleaseCargoLost.getText().toString());
        } else {
            mEntity.setLostPromise("");
        }
        if (binding.etReleaseCargoOverdue.getText() != null) {
            mEntity.setOverduePromise(binding.etReleaseCargoOverdue.getText().toString());
        } else {
            mEntity.setOverduePromise("");
        }
        if (binding.etReleaseCargoOther.getText() != null) {
            mEntity.setOtherPromise(binding.etReleaseCargoOther.getText().toString());
        } else {
            mEntity.setOtherPromise("");
        }
        //车辆运输监督要求
        if (binding.etReleaseCargoMark.getText() != null) {
            mEntity.setMark(binding.etReleaseCargoMark.getText().toString());
        } else {
            mEntity.setMark("");
        }
        //
        if (binding.etReleaseCargoAccount.getText() != null) {
            mEntity.setReceiptAccountRequire(binding.etReleaseCargoAccount.getText().toString());
        } else {
            mEntity.setReceiptAccountRequire("");
        }
        if (binding.etReleaseCargoOtherPayMark.getText() != null) {
            mEntity.setOtherPaymentRequire(binding.etReleaseCargoOtherPayMark.getText().toString());
        } else {
            mEntity.setOtherPaymentRequire("");
        }
        //判断自定义字段是否正确
        if (!loadFieldData()) {
            return;
        }
        if (binding.etCompany.getText() != null) {
            mEntity.setShipperOwnerUnit(binding.etCompany.getText().toString().trim());
        } else {
            mEntity.setShipperOwnerUnit("");
        }

        if (binding.etContacts.getText() != null) {
            mEntity.setShipperContact(binding.etContacts.getText().toString());
        } else {
            mEntity.setShipperContact("");
        }

        if (binding.etPhone.getText() != null) {
            String tel = binding.etPhone.getText().toString();
            if (!TextUtils.isEmpty(tel) && !CheckUtils.isPhoneNumberValid(tel)) {
                MToast.showToast(this, "请填写正确的联系电话");
                return;
            }
            mEntity.setShipperPhone(tel);
        } else {
            mEntity.setShipperPhone("");
        }

        Intent intent = new Intent();
        intent.putExtra(RouterKey.DATA, mEntity);
        setResult(RESULT_OK, intent);
        finish();
    }

    /**
     * 加载自定义字段
     */
    private boolean loadFieldData() {
        if (mCustomList != null && !mCustomList.isEmpty()) {
            Set<String> fieldName = new HashSet<>();
            //判断是否填写了自定义字段
            for (SingleItemEntity entity : mCustomList) {
                if (!fieldName.contains(entity.getLeftString())) {
                    fieldName.add(entity.getLeftString());
                } else {
                    MToast.showToast(this, "请检查新增字段名称是否有重复");
                    return false;
                }
                if (TextUtils.isEmpty(entity.getLeftString())) {
                    MToast.showToast(this, "请输入新增字段名称");
                    return false;
                }
                if (TextUtils.isEmpty(entity.getRightString())) {
                    MToast.showToast(this, String.format("请输入%s内容", entity.getLeftString()));
                    return false;
                }
            }
            //设置自定义字段
            mEntity.setCustomList(mCustomList);
        } else {
            mEntity.setCustomList(null);
        }
        return true;
    }
}
